<?php

namespace App\Http\Middleware;

use App\Consts\ExceptionCode;
use App\Consts\GlobalLoginConst;
use App\Consts\GlobalResultCode;
use App\Exceptions\Error;
use App\Models\Cache\Cache;
use App\Models\Cache\CacheKey;
use Closure;
use Illuminate\Http\Request;

class CheckLogin
{
    /**
     * Handle an incoming request.
     * 检查登录状态
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->cookie('token') ?: $request->header('token');

        // 没有token
        if (!$token) {
            return Error::handle(lang('Login error'), ExceptionCode::LOGIN_FAIL, GlobalResultCode::LOGIN_NOT_HAVE_TOKEN);
        }

        // token不在缓存中
        $isLogin = Cache::getInstance([
            'platform' => GlobalLoginConst::LOGIN_PLATFORM_WEB_STR,
            'token' => $token,
        ])->get(CacheKey::USER_LOGIN_STATUS);
        if (!$isLogin) {
            return Error::handle(lang('Login error'), ExceptionCode::LOGIN_FAIL, GlobalResultCode::LOGIN_TOKEN_NOT_EXISTS);
        }

        return $next($request);
    }
}
